<template>
  <GlobalDrawer
    v-model="visible"
    title="新增合同"
    size="80%"
    :before-close="handleClose"
    @confirm="handleConfirm"
  >
    <div class="drawer-content-wrapper">
      <el-form
        ref="formRef"
        :model="contractForm"
        :rules="rules"
        label-width="120px"
        label-position="right"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="form-section-title">基本信息</h3>
          <div class="form-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同名称" prop="name">
                  <el-input v-model="contractForm.name" placeholder="请输入合同名称" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同编号" prop="code">
                  <el-input v-model="contractForm.code" placeholder="请输入合同编号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="签约主体(乙方)" prop="subject_id">
                  <el-select
                    v-model="contractForm.subject_id"
                    placeholder="请选择签约主体公司"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in enterpriseList"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同类别" prop="cate_id">
                  <el-select
                    v-model="contractForm.cate_id"
                    placeholder="请选择合同类别"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in contractCategories"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户代表" prop="contact_name">
                  <el-input v-model="contractForm.contact_name" placeholder="请输入客户代表姓名" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="客户联系电话">
                  <el-input
                    v-model="contractForm.contact_mobile"
                    placeholder="请输入客户联系电话"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同金额" prop="cost">
                  <el-input v-model="contractForm.cost" placeholder="请输入合同金额">
                    <template #prepend>¥</template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="到账金额" prop="cost2">
                  <el-input v-model="contractForm.cost2" placeholder="请输入到账金额">
                    <template #prepend>¥</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同开始时间" prop="start_time">
                  <el-date-picker
                    v-model="contractForm.start_time"
                    type="date"
                    placeholder="选择合同开始时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同结束时间" prop="end_time">
                  <el-date-picker
                    v-model="contractForm.end_time"
                    type="date"
                    placeholder="选择合同结束时间"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 签订信息 -->
        <div class="form-section">
          <h3 class="form-section-title">签订信息</h3>
          <div class="form-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同签订人" prop="sign_uid">
                  <el-select
                    v-model="contractForm.sign_uid"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词搜索用户"
                    :remote-method="remoteSearchUsers"
                    :loading="userLoading"
                    @change="handleUserChange"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in userOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                      <span>{{ item.name }}</span>
                      <span
                        v-if="item.department"
                        style="float: right; color: #8492a6; font-size: 13px"
                      >
                        {{ item.department }}
                      </span>
                    </el-option>
                  </el-select>
                  <input type="hidden" v-model="contractForm.sign_name" />
                  <input type="hidden" v-model="contractForm.did" />
                  <input type="hidden" v-model="contractForm.sign_department" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同签订日期" prop="sign_time">
                  <el-date-picker
                    v-model="contractForm.sign_time"
                    type="date"
                    placeholder="选择合同签订日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 附件信息 -->
        <div class="form-section">
          <h3 class="form-section-title">附件信息</h3>
          <div class="form-container">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="合同附件">
                  <el-upload
                    ref="uploadRef"
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :on-remove="handleUploadRemove"
                    :file-list="fileList"
                    :auto-upload="false"
                    multiple
                    :limit="5"
                  >
                    <el-button type="primary">选择文件</el-button>
                    <template #tip>
                      <div class="el-upload__tip">
                        最多可上传5个文件，支持PDF、Word、Excel等格式
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 其他信息 -->
        <div class="form-section">
          <h3 class="form-section-title">其他信息</h3>
          <div class="form-container">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="合同备注">
                  <el-input
                    v-model="contractForm.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入合同备注"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
    </div>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { contractApi } from '../../../api/contract'
  import { cate } from '../../../api/home/cate'
  import { userApi } from '../../../api/user'
  import { GlobalDrawer } from '../../../components/common'

  // 定义props和emits
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    customerId: {
      type: [Number, String],
      required: true,
    },
    customerName: {
      type: String,
      default: '',
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  // 抽屉显示状态
  const visible = ref(false)

  // 表单引用
  const formRef = ref<InstanceType<typeof import('element-plus').ElForm>>()

  // 合同表单数据
  const contractForm = reactive({
    name: '',
    code: '',
    subject_id: '',
    cate_id: '',
    customer: '', // 客户名称（自动填充）
    customer_id: props.customerId, // 客户ID（自动填充）
    contact_name: '',
    contact_mobile: '',
    cost: '',
    cost2: '',
    cost3: '',
    start_time: '',
    end_time: '',
    sign_name: '',
    sign_uid: '',
    sign_department: '',
    did: '',
    sign_time: '',
    remark: '',
    types: 1,
    file_ids: '',
  })

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
    subject_id: [{ required: true, message: '请选择签约主体公司', trigger: 'change' }],
    cate_id: [{ required: true, message: '请选择合同类别', trigger: 'change' }],
    contact_name: [{ required: true, message: '请输入客户代表姓名', trigger: 'blur' }],
    cost: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
    cost2: [{ required: true, message: '请输入到账金额', trigger: 'blur' }],
    start_time: [{ required: true, message: '请选择合同开始时间', trigger: 'change' }],
    end_time: [{ required: true, message: '请选择合同结束时间', trigger: 'change' }],
    sign_uid: [{ required: true, message: '请选择合同签订人', trigger: 'change' }],
    sign_time: [{ required: true, message: '请选择合同签订日期', trigger: 'change' }],
  }

  // 企业列表
  const enterpriseList = ref<any[]>([])

  // 合同分类列表
  const contractCategories = ref<any[]>([])

  // 用户远程搜索相关
  const userOptions = ref<any[]>([])
  const userLoading = ref(false)

  // 上传相关
  const uploadRef = ref()
  const uploadUrl = ref(import.meta.env.VITE_API_BASE_URL + '/home/files/upload')
  const uploadHeaders = ref({
    Authorization: 'Bearer ' + localStorage.getItem('token'),
  })
  const fileList = ref([])

  // 监听modelValue变化
  const handleModelValueChange = (val: boolean) => {
    visible.value = val
    if (val) {
      // 打开抽屉时，自动填充客户信息
      if (props.customerName) {
        contractForm.customer = props.customerName
      }
      // 初始化数据
      initData()
    } else {
      // 关闭抽屉时重置表单
      resetForm()
    }
  }

  // 监听抽屉关闭
  const handleClose = (): boolean => {
    emit('update:modelValue', false)
    return true
  }

  // 确认提交
  const handleConfirm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          // 处理时间字段
          const submitData: any = { ...contractForm }

          if (submitData.start_time && typeof submitData.start_time !== 'string') {
            submitData.start_time = new Date(submitData.start_time).toISOString().split('T')[0]
          }
          if (submitData.end_time && typeof submitData.end_time !== 'string') {
            submitData.end_time = new Date(submitData.end_time).toISOString().split('T')[0]
          }
          if (submitData.sign_time && typeof submitData.sign_time !== 'string') {
            submitData.sign_time = new Date(submitData.sign_time).toISOString().split('T')[0]
          }

          const response: any = await contractApi.addContract(submitData)

          if (response.code === 0) {
            ElMessage.success('新增合同成功')
            emit('success')
            handleClose()
          } else {
            ElMessage.error(response.msg || '新增合同失败')
          }
        } catch (error) {
          ElMessage.error('新增合同失败')
        }
      }
    })
  }

  // 处理用户选择变更
  const handleUserChange = (userId: number) => {
    const selectedUser = userOptions.value.find(item => item.id === userId)

    if (selectedUser) {
      contractForm.sign_name = selectedUser.name

      if (selectedUser.did) {
        contractForm.did = selectedUser.did
      }
      if (selectedUser.department) {
        contractForm.sign_department = selectedUser.department
      }

      ElMessage.success('用户选择成功')
    }
  }

  // 上传成功处理
  const handleUploadSuccess = (response: any, file: any, fileList: any) => {
    if (response.code === 0 && response.data && response.data.id) {
      const uploadedFile = {
        id: response.data.id,
        name: response.data.name,
        size: response.data.filesize,
        url: response.data.filepath,
      }

      fileList.value = [...fileList.value, uploadedFile]

      const fileIds = fileList.value.map((item: any) => item.id).join(',')
      contractForm.file_ids = fileIds

      ElMessage.success('文件上传成功')
    } else {
      ElMessage.error(response.msg || '文件上传失败')
    }
  }

  // 上传失败处理
  const handleUploadError = (error: any, file: any, fileList: any) => {
    ElMessage.error('文件上传失败')
  }

  // 文件移除处理
  const handleUploadRemove = (file: any, fileList: any) => {
    fileList.value = fileList

    const fileIds = fileList.value.map((item: any) => item.id).join(',')
    contractForm.file_ids = fileIds
  }

  // 远程搜索用户
  const remoteSearchUsers = async (query: string) => {
    if (query === '') {
      userOptions.value = []
      return
    }

    userLoading.value = true
    try {
      const response = await userApi.getUserList({ keywords: query, page: 1, limit: 20 })

      if (response.code === 0 && response.data) {
        userOptions.value = (response.data.list || response.data).map((user: any) => ({
          id: user.id,
          name: user.name || user.username || user.real_name,
          department: user.department_name || user.dept_name || user.department || '',
          did: user.department_id || user.dept_id || '',
          username: user.username,
        }))
      } else {
        userOptions.value = []
        ElMessage.warning(response.msg || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表错误:', error)
      userOptions.value = []
      ElMessage.error('获取用户列表失败')
    } finally {
      userLoading.value = false
    }
  }

  // 获取企业列表
  const getEnterpriseList = async () => {
    try {
      const response: any = await cate.getEnterpriseList()

      if (response.code === 0) {
        if (Array.isArray(response.data)) {
          enterpriseList.value = response.data
        } else if (
          response.data &&
          typeof response.data === 'object' &&
          (response.data as any).list
        ) {
          enterpriseList.value = (response.data as any).list
        } else if (response.data && typeof response.data === 'object') {
          enterpriseList.value = Object.values(response.data)
        } else {
          enterpriseList.value = []
        }
      } else {
        ElMessage.error(response.msg || '获取企业列表失败')
      }
    } catch (error) {
      console.error('获取企业列表失败:', error)
      ElMessage.error('获取企业列表失败')
      enterpriseList.value = []
    }
  }

  // 获取合同分类列表
  const getContractCategories = async () => {
    try {
      const response: any = await contractApi.getContractCategories()

      if (response.code === 0) {
        if (Array.isArray(response.data)) {
          contractCategories.value = response.data
        } else if (
          response.data &&
          typeof response.data === 'object' &&
          (response.data as any).list
        ) {
          contractCategories.value = (response.data as any).list
        } else if (response.data && typeof response.data === 'object') {
          contractCategories.value = Object.values(response.data)
        } else {
          contractCategories.value = []
        }
      } else {
        ElMessage.error(response.msg || '获取合同分类失败')
      }
    } catch (error) {
      console.error('获取合同分类失败:', error)
      ElMessage.error('获取合同分类失败')
      contractCategories.value = []
    }
  }

  // 初始化数据
  const initData = () => {
    getEnterpriseList()
    getContractCategories()
    contractForm.customer = props.customerName || ''
    contractForm.customer_id = props.customerId
  }

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }

    contractForm.sign_name = ''
    contractForm.sign_department = ''
    contractForm.remark = ''
    contractForm.cost3 = ''
    contractForm.file_ids = ''

    userOptions.value = []
    fileList.value = []

    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
  }

  onMounted(() => {
    // 初始化数据
    getEnterpriseList()
    getContractCategories()
  })

  defineExpose({
    handleConfirm,
  })

  watch(() => props.modelValue, handleModelValueChange, { immediate: true })
</script>

<style scoped>
  .drawer-content-wrapper {
    padding: 20px;
  }

  .form-section {
    margin-bottom: 30px;
  }

  .form-section::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 4px;
    height: 22px;
    background-color: #409eff;
    border-radius: 2px;
  }

  .form-section-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 15px;
    padding-bottom: 10px;
    padding-left: 15px;
    border-bottom: 1px solid #ebeef5;
    position: relative;
  }

  .form-container {
    background-color: #fafafa;
    padding: 20px;
    border-radius: 6px;
    margin-bottom: 20px;
  }
</style>
